package com.deep.cart.interceptor;

import com.deep.cart.model.dto.UserInfoDTO;
import com.deep.common.model.constant.AuthConstant;
import com.deep.common.model.constant.CartConstant;
import com.deep.common.model.dto.MemberResponseVO;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 购物车拦截器
 * 在目标方法执行之前，判断用户登录状态，并封装传递给controller目标请求
 *
 * @author Deep
 * @date 2022/2/9
 */
@Component
public class CartInterceptor implements HandlerInterceptor {
    /**
     * ThreadLocal当前线程内共享数据
     * ThreadLocal核心就是一个Map<Thread,Object>,每一个线程(Thread)对应一个数据(Object),从而实现线程间的互不干扰
     * 每处理一个请求，tomcat都会为该请求创建一个线程处理（拦截器->controller->service->dao）
     */
    public static ThreadLocal<UserInfoDTO> userInfoDTOThreadLocal = new ThreadLocal<>();

    /**
     * 方法执行之前拦截(请求到达之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        // 从session中获取当前用户信息
        HttpSession session = request.getSession();
        MemberResponseVO member = (MemberResponseVO) session.getAttribute(AuthConstant.LOGIN_USER);
        if (member != null) {
            // 用户已登录
            userInfoDTO.setUserId(member.getId());
        }
        // 从cookie中获取user-key
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                // 客户端cookie中存储了user-key
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoDTO.setUserKey(cookie.getValue());
                    // 标识客户端已经存储了 user-key
                    userInfoDTO.setTempUser(true);
                }
            }
        }
        // 若浏览器中无缓存cookie
        if (!StringUtils.hasLength(userInfoDTO.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            // user-key
            userInfoDTO.setUserKey(uuid);
        }
        // 目标方法执行之前
        userInfoDTOThreadLocal.set(userInfoDTO);
        return true;
    }

    /**
     * 业务执行之后，让浏览器保存临时用户user-key
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 获取当前用户的值
        UserInfoDTO userInfoTo = userInfoDTOThreadLocal.get();
        // 1、判断是否登录；2、判断是否创建user-token的cookie
        if (userInfoTo != null && !userInfoTo.isTempUser()) {
            //创建一个cookie
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("mall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
